/*
 * Canvas Game Engine - Shape Module
 *
 * version: 0.1
 *
 * author: Fabio Rotondo <fabio@rotondo.it>
 *
 */

// Creates a new CGE Shape
// Parameters:
//
// 	- sh: 	CGEShapeHandler instance
// 	- url:  Image URL
// 	- name: shape name
// 	- w:	shape width
// 	- h: 	shape height
function CGEShape ( sh, url, name, w, h )
{
	var self = this;

	this.sh     = sh;
	this.image  = CGE.image_handler.add ( url, "sh-" + name );
	this.w	    = w;
	this.h	    = h;

	this.save_canvas = CGE.canvas_handler.add ( "sh-" + name, this.w, this.h );

	this.alpha = 100;

	this.save_background = true;
}

CGEShape.prototype.blit = function ( x, y, alpha )
{
	var ctxt = CGE.canvas.ctxt;
	var _a = CGE.canvas.ctxt.globalAlpha;

	if ( alpha === undefined ) alpha = this.alpha;

	if ( alpha < 0 ) alpha = 0;
	if ( alpha > 100 ) alpha = 100;

	this.alpha = alpha;
	this.x = x;
	this.y = y;

	if ( this.x < 0 ) this.x = 0;
	if ( this.y < 0 ) this.y = 0;
	if ( this.x + this.w > CGE.canvas.w ) this.x = CGE.canvas.w - this.w;
	if ( this.y + this.h > CGE.canvas.h ) this.y = CGE.canvas.h - this.h;

	// console.debug ( "X: %s Y: %s - W: %s %s", this.x, this.y, CGE.canvas.w, CGE.canvas.h );

	// Save the original canvas CTXT inside the save_canvas
	if ( this.save_background ) this.save_canvas.ctxt.drawImage ( CGE.canvas.canvas, this.x, this.y, this.w, this.h, 0, 0, this.w, this.h );

	this.image.blit ( x, y, this.alpha, this.w, this.h );
};

CGEShape.prototype.unblit = function ()
{
	if ( this.save_background ) CGE.canvas.ctxt.drawImage ( this.save_canvas.canvas, this.x, this.y );
};

function CGEShapeHandler ()
{
	this._tot = 0;		// Total amount of resources in memory

	this.shapes = {};
}

CGEShapeHandler.prototype.add = function ( url, name, w, h )
{
	var sh;

	if ( ! name ) name = url;

	// You cannot have two images with the same name (identifier)
	if ( this.shapes [ name ] ) return this.shapes [ name ];

	this._tot += 1;

	sh = new CGEShape ( this, url, name, w, h );
	this.shapes [ name ] = sh;

	return sh;
};

CGEShapeHandler.prototype.get = function ( name )
{
	return this.shapes [ name ];
};

CGEShapeHandler.prototype.ready = function () { return true; };

// Register the ShapeHandler to the system
CGE.register ( "shape_handler", new CGEShapeHandler () );
